package com.abocode.aichat.app.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/***
 *  Created by guanxf on 2015/12/16.
 */
public class DESUtils {

	static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

	public static String encrypt(String encryptString,String encryptKey){
		byte[] dkey = encryptKey.getBytes();
		byte[] encryptedData=null;
		try {
			DESKeySpec dks = new DESKeySpec(dkey);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(dks);
			IvParameterSpec zeroIv = new IvParameterSpec(iv);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, securekey, zeroIv);
			encryptedData = cipher.doFinal(encryptString.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Base64.encodeBase64String(encryptedData);
	}

	public static String decrypt(String decryptString,String encryptKey){
		byte[] byteMi = Base64.decodeBase64(decryptString);
		byte[] dkey = encryptKey.getBytes();
		byte decryptedData[]=null;
		try {
			DESKeySpec dks = new DESKeySpec(dkey);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(dks);
			IvParameterSpec zeroIv = new IvParameterSpec(iv);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, securekey, zeroIv);
			decryptedData = cipher.doFinal(byteMi);
		}catch (Exception e){
         e.printStackTrace();
		}
		return new String(decryptedData);
	}
}
